// set function parseTime,formatTime to filter
export { parseTime, formatTime } from '@/utils'

function pluralize(time, label) {
  if (time === 1) {
    return time + label
  }
  return time + label + 's'
}

export function timeAgo(time) {
  const between = Date.now() / 1000 - Number(time)
  if (between < 3600) {
    return pluralize(~~(between / 60), ' minute')
  } else if (between < 86400) {
    return pluralize(~~(between / 3600), ' hour')
  } else {
    return pluralize(~~(between / 86400), ' day')
  }
}

export function fomatterTime(t) {
  const fTime = t || 0
  let time = parseInt(fTime) + '秒'
  if (parseInt(fTime) > 60) {
    var second = parseInt(fTime) % 60
    var min = parseInt(fTime / 60)
    time = min + '分' + second + '秒'

    if (min > 60) {
      min = parseInt(fTime / 60) % 60
      var hour = parseInt(parseInt(fTime / 60) / 60)
      time = hour + '小时' + min + '分' + second + '秒'

      if (hour > 24) {
        hour = parseInt(parseInt(fTime / 60) / 60) % 24
        var day = parseInt(parseInt(parseInt(fTime / 60) / 60) / 24)
        time = day + '天' + hour + '小时' + min + '分' + second + '秒'
      }
    }
  }
  return time
}

/* 数字 格式化*/
export function numberFormatter(num, digits) {
  const si = [
    { value: 1E18, symbol: 'E' },
    { value: 1E15, symbol: 'P' },
    { value: 1E12, symbol: 'T' },
    { value: 1E9, symbol: 'G' },
    { value: 1E6, symbol: 'M' },
    { value: 1E3, symbol: 'k' }
  ]
  for (let i = 0; i < si.length; i++) {
    if (num >= si[i].value) {
      return (num / si[i].value + 0.1).toFixed(digits).replace(/\.0+$|(\.[0-9]*[1-9])0+$/, '$1') + si[i].symbol
    }
  }
  return num.toString()
}

export function toThousandFilter(num) {
  return (+num || 0).toString().replace(/^-?\d+/g, m => m.replace(/(?=(?!\b)(\d{3})+$)/g, ','))
}

/**
 * 格式化考试用户，传入单位是分钟
 */
export function fomatterExamTime(str) {
  let time = ''
  var h = Math.floor(str / 60)
  var m = Math.floor(str % 60)
  if (h) {
    if (m) {
      time = h + '小时' + m + '分'
    } else {
      time = h + '小时'
    }
  } else {
    if (m) {
      time = m + '分'
    }
  }
  return time
}

export function newFormatTime(time, option) {
  if (!time) {
    return
  }
  const d = new Date(time.replace(/-/g, '/'))
  if (option) {
    return parseTime(time, option)
  } else {
    return (
      d.getFullYear() + '年' +
        (d.getMonth() + 1) +
        '月' +
        d.getDate() +
        '日'
        /* +
        d.getHours() +
        '时' +
        d.getMinutes() +
        '分'*/
    )
  }
}

